import { baseUrl } from './baseConfig.js'
import store from '../store/index.js'

export const request = (method, url, opts) => {
	if (!opts.showLoading) {
		uni.showLoading({
			mask: false
		})
	}
	const { data, success, complete, successMsg, errorMsg, fail } = opts
	let httpDefaultOpts = {
		url: baseUrl + url,
		data: data,
		method: method,
		header: method == 'get' ? {
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
			"Authorization": store.getters.userInfo && store.getters.userInfo.token ? store.getters.userInfo.token :
				''
		} : {
			'X-Requested-With': 'XMLHttpRequest',
			"Content-Type": "application/json;charset=UTF-8",
			"Authorization": store.getters.userInfo && store.getters.userInfo.token ? store.getters.userInfo
				.token : ''
		},
		dataType: 'json',
		success: (res) => {
			const { data: { data, meta } } = res
			uni.hideLoading()
			if (meta.status == 200) {
				if (!!successMsg) {
					console.log(successMsg)
					uni.showToast({
						title: successMsg,
						icon: 'none',
						duration: 2000
					});
				}

				success(data)
			} else {
				uni.showToast({
					title: meta.msg,
					icon: 'none',
					duration: 2000
				});
			}
		},
		fail: (e) => {
			if (errorMsg) {
				uni.showToast({
					title: errorMsg,
					duration: 2000
				});
			}
			if (fail && typeof(fail) === 'function') {
				fail(e)

			}
			uni.hideLoading()
		},
		complete: () => {
			if (complete && typeof(complete) === 'function') {
				complete()

			}
			uni.hideLoading()
		}
	}
	uni.request(httpDefaultOpts)
};

